package cn.xawl.gulimall.search.service.impl;

import cn.xawl.common.to.es.SkuEsModel;
import cn.xawl.gulimall.search.config.ESConfig;
import cn.xawl.gulimall.search.constant.EsIndexConstant;
import cn.xawl.gulimall.search.service.EsProductService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author lh
 * @date 2020/08/15 15:51:17
 **/
@Slf4j
@Service
public class EsProductServiceImpl implements EsProductService {

    @Qualifier(value = "esClient")
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public void upProduct(List<SkuEsModel> skuEsModels) {
        try {
            BulkRequest bulkRequest = new BulkRequest();
            for (SkuEsModel skuEsModel : skuEsModels) {
                IndexRequest indexRequest = new IndexRequest(EsIndexConstant.PRODUCT_INDEX);
                indexRequest.id(String.valueOf(skuEsModel.getSkuId()));
                String jsonString = JSON.toJSONString(skuEsModel);
                indexRequest.source(jsonString, XContentType.JSON);
                bulkRequest.add(indexRequest);
            }
            BulkResponse response = restHighLevelClient.bulk(bulkRequest, ESConfig.COMMON_OPTIONS);

        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException("es保存索引时异常");
        }
    }
}
